package me.younian.transmit;

import org.apache.log4j.Logger;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;


public class SocketServerClient implements Runnable {
    private static final Logger logger = Logger.getLogger(SocketServerClient.class);

    private ServerSocket socket = null;
    private Socket client = null;

    public void oneServer() {
        try {
            socket = new ServerSocket(5209);
            //b)指定绑定的端口，并监听此端口。
            System.out.println("1-Client服务器启动成功");
            //创建一个ServerSocket在端口5209监听客户请求
        } catch (Exception e) {
            e.printStackTrace();
        }

        AcceptTask acceptTask = new AcceptTask();
        new Thread(acceptTask).start();
    }

    @Override
    public void run() {
        oneServer();
    }

    public ServerSocket getSocket() {
        return socket;
    }

    public void setSocket(ServerSocket socket) {
        this.socket = socket;
    }

    public Socket getClient() {
        return client;
    }

    public void setClient(Socket client) {
        this.client = client;
    }

    private class AcceptTask implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    client = socket.accept();
                    //client.setSoTimeout(1000);
                    //logger.info("update to :" + client.hashCode());
                    logger.info("=== Client Updated");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
